package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.aliyuncs.utils.StringUtils;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.FocusUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.FocusUser;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class VideosService {
    @Autowired
    private FastFileStorageClient fastFileStorageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Autowired
    private OssTemplate ossTemplate;
    @DubboReference
    private VideoApi videoApi;
    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private FocusUserApi focusUserApi;
    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 视频发布
     *
     * @param videoThumbnail
     * @param videoFile
     */
    @CacheEvict(value = "videos", allEntries = true) //开启EnableAsync缓存
    public void smallVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //首先判断文件和文件封面是否为空
        if (videoThumbnail.isEmpty() || videoFile.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }

        //获取文件名字
        String filename = videoFile.getOriginalFilename();
        //从.截取 拼接名字
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        //将视频上传到FastDFS 获取访问的url
        StorePath storePath = fastFileStorageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        //拼接视频访问地址
        String videoUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        //将封面图片上传到阿里云，获取访问的url
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //构建video对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("南峋摄影");
        //生成日志登录
        mqMessageService.sendLogMessage(UserHolder.getUserId(), "0301", "video", null);
        //调用api保存数据
        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)) {
            throw new BusinessException(ErrorResult.error());
        }
    }

    /**
     * 查看视频列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    @Cacheable(
            value = "videos",
            key = "T(com.tanhua.server.interceptor.UserHolder).getUserId()+'_'+#page+'_'+#pagesize")
    public PageResult findAllSmallVideos(Integer page, Integer pagesize) {
        //从redis中获取数据
        String redisKey = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String redisValue = (String) redisTemplate.opsForValue().get(redisKey);
        List<Video> list = new ArrayList<>();
        int redisPages = 0;
        //判断有无数据
        if (!StringUtils.isEmpty(redisValue)) {
            //如果不为空 进行切割
            String[] values = redisValue.split(",");
            //判断起始页数是否小于总数
            if ((page - 1) * pagesize < values.length) {
                //查询当前页推荐的所有的id
                List<Long> vids = Arrays.stream(values).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e -> Long.valueOf(e))
                        .collect(Collectors.toList());
                list = videoApi.findmovementsById(vids);
            }
            redisPages = PageUtil.totalPage(values.length, pagesize);
        }
        //如果redis数据不存在，分页查询视频数据
        if (list.isEmpty()) {
            //查询总页数
            list = videoApi.queryVideoList(page - redisPages, pagesize);
        }
        //获取视频列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //查询所有用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<VideoVo> vos = new ArrayList<>();
        //构建返回值
        for (Video video : list) {
            UserInfo userInfo = map.get(video.getUserId());
            if (userInfo != null) {
                VideoVo vo = VideoVo.init(userInfo, video);
                //设置key 判断用户是被已经被关注
                String attentionId = String.valueOf(video.getUserId());
                String redisKey1 = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
                //查找redis中的数据
                Boolean member = redisTemplate.opsForSet().isMember(redisKey1, attentionId);
                if (member){
                    vo.setHasFocus(1);
                }
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0, vos);
    }

    /**
     * 视频用户关注
     *
     * @param uid
     * @return
     */
    @CacheEvict(value = "videos", allEntries = true)
    public void userFocus(Long uid) {
        //设置key
        String attentionId = String.valueOf(uid);
        String redisKey = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        //创建对象
        FocusUser focusUser = new FocusUser();
        //将数据存入redis
        Boolean member = redisTemplate.opsForSet().isMember(redisKey, attentionId);
        //判断redis中是否有数据
        if (member) {
            throw new BusinessException(ErrorResult.FocusError());
        } else if (uid.equals(UserHolder.getUserId())) {
            throw new BusinessException(ErrorResult.FocusUserError());
        } else {
            focusUser.setUserId(UserHolder.getUserId());
            focusUser.setAttentionId(uid);
            focusUser.setCreated(System.currentTimeMillis());
            focusUser.setUpdated(System.currentTimeMillis());
            //将关注用户信息保存到redis缓存中
            redisTemplate.opsForSet().add(redisKey, focusUser);
            //保存数据
            focusUserApi.save(focusUser);
        }
    }

    /**
     * 取消视频用户关注
     *
     * @param uid
     * @return
     */
    public void userUnFocus(Long uid) {
        //设置key
        String attentionId = String.valueOf(uid);
        String redisKey = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        //将数据存入redis
        Boolean member = redisTemplate.opsForSet().isMember(redisKey, attentionId);
        //判断redis中是否有数据,有匹配到的数据就进行删除
        if (!member) {
            //删除数据库的数据
            focusUserApi.delete(uid,UserHolder.getUserId());
            //删除redis中缓存数据
            redisTemplate.delete(redisKey);
        }
    }
}
